include ApplicationHelper

class ContactProfilesController < ApplicationController
  before_filter :load_data

  #control general de acceso cancan, segun los permisos definidos en ability.rb
  authorize_resource :resource => :contact_profiles

  def load_data
    @country_count_columns_by_row = Setting.view_contact_profile_countries_by_row
    @thematic_count_columns_by_row = Setting.view_contact_profile_thematics_by_row

    if I18n.locale == 'es'
      @thematics = Thematic.find(:all, :order => "name_web_es")
    else
      @thematics = Thematic.find(:all, :order => "name_web_en")
    end

    @countries = Country.find(:all, :conditions => "use_for_sale = true", :order => "name")
  end

  def index
    contact = Contact.find_by_user_id(current_user.id)

    @profiles_country = []
    @profiles_thematic = []
    @profiles_tag = []
    if !contact.nil?
      profiles = Profile.find(:all, :conditions => ["contact_id = ? and reference_type <> 'Descriptor'", contact.id])
      profiles.each do |profile|
        if profile.reference_type == "Thematic"
          @profiles_thematic << profile.reference_id
        end
        if profile.reference_type == "Country"
          @profiles_country << profile.reference_id
        end
      end

      profiles = Profile.find(:all, 
                              :joins => "LEFT OUTER JOIN descriptors ON descriptors.id = reference_id",
                              :conditions => ["contact_id = ? and reference_type = 'Descriptor'", contact.id],
                              :order => "descriptors.description")
      profiles.each do |p|
        @profiles_tag << p.reference
      end
    end

    # el parametro :load_tag_for_session solo se carga desde el will_paginate para saber que hay que paginar sobre
    # la collection que tenemos en memoria
    if params[:load_tag_for_session].nil? || params[:load_tag_for_session] == "false"
      # significa que es la primera vez que entro a la pagina o que estoy refrescando y quiero cargar la lista
      # de tags que hay en la base
      session[:profiles_tag] = @profiles_tag
    else
      # significa que estoy viniendo de un add o delete de tags -> tengo que mostrar lo que esta en memoria y no
      # lo de la base
      if session[:profiles_tag].nil?
        session[:profiles_tag] = @profiles_tag
      else
        @profiles_tag = session[:profiles_tag]
      end
    end

    @total_profiles_tag, @profiles_tag = tags_paginate
  end



  def update
    @profiles_tag = session[:profiles_tag]
    contact = Contact.find_by_user_id(current_user.id)

    profiles_country_id = []
    profiles_thematic_id = []

    if !params["profile"].nil?
      if !params["profile"]["thematics"].nil?
        profiles_thematic_id = params["profile"]["thematics"]
      else
        profiles_thematic_id = []
      end
      if !params["profile"]["countries"].nil?
        profiles_country_id = params["profile"]["countries"]
      else
        profiles_country_id = []
      end
    end

    if !contact.nil?

      # THEMATICS

      #borro de la base las que estan actualmente en la base y no en el array en memoria
      contact_profiles_thematic_database = Profile.find(:all, :conditions => ["contact_id = ? and reference_type = 'Thematic'", contact.id])
      contact_profiles_thematic_database.each  do |profile_database|
        if !profiles_thematic_id.include?(profile_database.reference_id)
          profile_database.destroy
        end
      end

      #agrego a la base las que solo esten en el array en memoria y no en la base
      profiles_thematic_id.each do |reference_id|
        if Profile.count(:conditions => ["contact_id = ? and reference_type = 'Thematic' and reference_id = ?", contact.id, reference_id.to_i]) == 0
          Profile.create(:contact_id => contact.id, :reference_type => "Thematic", :reference_id => reference_id.to_i, :excluded => false)
        end
      end

      #COUNTRIES

      #borro de la base las que estan actualmente en la base y no en el array en memoria
      contact_profiles_country_database = Profile.find(:all, :conditions => ["contact_id = ? and reference_type = 'Country'", contact.id])
      contact_profiles_country_database.each  do |profile_database|
        if !profiles_country_id.include?(profile_database.reference_id)
          profile_database.destroy
        end
      end

      #agrego a la base las que solo esten en el array en memoria y no en la base
      profiles_country_id.each do |reference_id|
        if Profile.count(:conditions => ["contact_id = ? and reference_type = 'Country' and reference_id = ?", contact.id, reference_id.to_i]) == 0
          Profile.create(:contact_id => contact.id, :reference_type => "Country", :reference_id => reference_id.to_i, :excluded => false)
        end
      end

      #TAGS

      #borro de la base las que estan actualmente en la base y no en el array en memoria
      profiles_tag_database = Profile.find(:all, :conditions => ["contact_id = ? and reference_type = 'Descriptor'", contact.id])
      profiles_tag_database.each  do |profile_database|
        if !@profiles_tag.include?(profile_database.reference)
          profile_database.destroy
        end
      end

      #agrego a la base las que solo esten en el array en memoria y no en la base
      @profiles_tag.each do |tag|
        if Profile.count(:conditions => ["contact_id = ? and reference_type = 'Descriptor' and reference_id = ?", contact.id, tag.id]) == 0
          Profile.create(:contact_id => contact.id, :reference => tag, :excluded => false)
        end
      end

      #se actualiza la session
      session[:profiles_tag]=nil

      flash[:notice] = t('msg_record_successfully_updated')
    end


    redirect_to :action => :index
  end

  def add_tag
    # se obtienen los tags que se encuentran en la session
    @profiles_tag = session[:profiles_tag]

    #se busca si el tag que se quiere agregar es valido o ya esta en la lista
    tag = Descriptor.find(:first, :conditions => "upper(description) = upper('#{params['tag']}')")
    if !tag.nil?
      if !@profiles_tag.include?(tag)
        @profiles_tag << tag
      else
        @message = t('lbl_contact_profile_tag_already_exist')
      end
    else
      @message = t('lbl_tag_not_exist')
    end

    #se actualiza la session
    session[:profiles_tag] = @profiles_tag

    @total_profiles_tag, @profiles_tag = tags_paginate
    render :partial=>'contact_profiles_tag_list' , :layout=>false
  end

  def delete_tag
    @profiles_tag = session[:profiles_tag]
    @profiles_tag.delete_if { |tag| tag.id == params['tag'].to_i  }

    #se actualiza la session
    session[:profiles_tag] = @profiles_tag

    @total_profiles_tag, @profiles_tag = tags_paginate
    render :partial=>'contact_profiles_tag_list' , :layout=>false
  end

  def auto_complete_tag
    @tags= Descriptor.find(:all, :conditions => ["upper(description) like upper(?)", "#{params[:tag]}%"], :order=>:description)
    render :layout=>false
  end

  def tags_paginate
    total = @profiles_tag.length
    tags = @profiles_tag

    # hay que hacer el paginado sin tener un modelo asociado.
    current_page = params[:page] || 1
    current_page = current_page.to_i
    per_page = count_record_per_page :contact_profiles_descriptors

    tags = WillPaginate::Collection.create(current_page, per_page, total) do |pager|
      start = (current_page-1)*per_page
      pager.replace(@profiles_tag[start, per_page])
    end

    return total, tags
  end

end
